package cm.example.shoppingplatformspringboot.service;

import cm.example.shoppingplatformspringboot.entity.ShopCarDTO;
import cm.example.shoppingplatformspringboot.mapper.CartMapper;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CartService {
    @Resource
    private CartMapper cartMapper;

    //查看购物车
    public List<ShopCarDTO> selectCartByUserId(int userId) {
        return cartMapper.selectCartByUserId(userId);
    }

    // 添加购物车
    @Transactional(rollbackFor = Exception.class)
    public int insertShopCart(@NotNull ShopCarDTO shopCarDTO) {
        // 1. 检查是否已存在该商品项
        ShopCarDTO existingItem = cartMapper.selectByUserIdAndGoodId(shopCarDTO.getUserid(), shopCarDTO.getGoodid());

        if (existingItem != null) {
            // 2. 存在：更新数量（累加）
            int newNum = existingItem.getNum() + shopCarDTO.getNum();
            return cartMapper.updateCartItemNum(existingItem.getId(), newNum);
        } else {
            // 3. 不存在：新增商品项并关联到购物车
            int cartItem = cartMapper.insertCartItem(shopCarDTO);
            int goodItemId = shopCarDTO.getGooditemid();
            int shopCar = cartMapper.insertShopCart(shopCarDTO.getUserid(), goodItemId);
            return cartItem + shopCar;
        }
    }

    // 修改购物车商品项数量
    @Transactional(rollbackFor = Exception.class)
    public int updateCartItemNum(int id, int num) {
        if (num == 0) {
            // 1. 数量为0时，删除商品项
            // 1.1 查询商品项所属用户ID
            Integer userId = cartMapper.getUserIdByGoodItemId(id);
            if (userId == null) {
                throw new RuntimeException("商品项不存在");
            }
            // 1.2 调用删除方法
            return deleteCartItem(userId, id);
        } else if (num > 0) {
            // 2. 数量大于0时，更新数量
            return cartMapper.updateCartItemNum(id, num);
        } else {
            // 3. 数量为负数时，抛出异常
            throw new IllegalArgumentException("商品数量不能为负数");
        }
    }

    // 删除购物车商品项
    @Transactional(rollbackFor = Exception.class)
    public int deleteCartItem(int userid, int gooditemid) {
        // 1. 验证商品项是否属于当前用户（防止越权删除）
        Integer itemUserId = cartMapper.getUserIdByGoodItemId(gooditemid);
        if (itemUserId == null || itemUserId != userid) {
            throw new RuntimeException("无权删除该商品项");
        }

        // 2. 先删除购物车关联记录（避免外键约束问题）
        int deleteShopCart = cartMapper.deleteShopCart(userid, gooditemid);

        // 3. 再删除商品项
        int deleteCarItem = cartMapper.deleteCarItem(gooditemid);

        return deleteShopCart + deleteCarItem;
    }

    // 清空购物车
    @Transactional(rollbackFor = Exception.class)
    public int clearCart(int userid) {
        // 1. 删除购物车关联记录
        int deleteShopCart = cartMapper.deleteAllShopCartByUserId(userid);

        // 2. 删除用户所有商品项
        int deleteCarItems = cartMapper.deleteAllCarItemsByUserId(userid);

        return deleteShopCart + deleteCarItems;
    }
}
